//引入React及Component，Fragment
import React, { Component, Fragment } from 'react'
//引入antd相关组件
import {
  Card,
  Table,
  Button,
  Popover,
  Tag,
  Modal,
  notification,
  Typography,
  Icon,
  Select
} from 'antd';
//引入moment.js用于格式化时间
import moment from 'moment'
//引入XLSX用于导出excel表
import XLSX from 'xlsx'
//基于axios封装的ajax请求方法
import { getArticleList, deleteArticleById } from '../../requests'

const ButtonGroup = Button.Group
const { Text } = Typography

export default class Article extends Component {
  //初始化Article,将内部的isLoading改为true，用一个变量将传入的数据存下来
  constructor() {
    super()
    //把生成数据的模板初始化，这样就可以删除与选择了
    this.initialColumns = [{
      title: '标题',
      //正常的情况下，只需要把这个dataIndex和数据的key绑定一下即可
      dataIndex: 'title',
      key: 'title',
    }, {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
    }, {
      title: '创建时间',
      //重新处理使用render方法
      render: (text, record, index) => {
        //使用moment.js渲染时间
        return moment(record.creatAt).format('YYYY年MM月DD日 hh:mm:ss')
      },
      key: 'createAt',
    },
    {
      title: '阅读量',
      //需要自定义渲染用这个方法
      render: (text, record, index) => {
        //判断阅读量改变颜色
        return <Tag color={record.amount > 300 ? "red" : "green"}>{record.amount}</Tag>
      },
      key: 'amount',
    }, {
      title: '操作',
      key: 'action',
      render: (text, record, index) => {
        return (

          <ButtonGroup>
            <Popover content={`点击编辑${record.title}`}>
              <Button onClick={this.toEdit.bind(this, record)} size="small" type="primary">编辑</Button>
            </Popover>
            <Popover content={`点击删除${record.title}`}>
              <Button
                size="small"
                type="danger"
                onClick={this.handleArticleDelete.bind(this, record)}
              >删除</Button>
            </Popover>
          </ButtonGroup>
        )
      }
    }]
    //初始化的state
    this.state = {
      dataSource: [],
      isLoading: true,
      edModalVisible: false,
      confirmloading: false,
      clickArticleId: null,
      clickArticleTitle: "",
      columnsOptions: ['作者', '阅读量', '创建时间'],
      columns: this.initialColumns
    }
  }


  //请求ajxa数据
  getData = () => {
    getArticleList()
      .then(resp => {
        if (resp.data.code === 200) {
          this.setState({
            isLoading: false,
            dataSource: resp.data.data
          })
        }
      })
      .catch(error => {
        //真实的项目得做大量的错误处理
        console.log(error)
      }
      )
  }

  //删除数据方法
  hanleCancleDelete = () => {
    this.setState({
      edModalVisible: false,
      confirmLoading: false,
    })
  }
  //点击编辑跳转页面
  toEdit = (record) => {
    console.log(this.props)
    const{
      id,
      title
    }=record
  this.props.history.push(`/admin/article/edit/${id}`,{
    title
  })
  }
  //弹出框的ok事件
  handleDeleteButtonClick = () => {
    this.setState({
      confirmloading: true,
    }, () => {
      deleteArticleById(this.state.clickArticleId)
        .then(res => {
          console.log(res)
          if (res.data.code === 200) {
            //再次请求数据
            this.getData()
            notification.success({
              message: res.data.data.errorMsg,
              description: '它已经没啦，你这个凶手，坏淫',
              duration: 2
            })
            //删除后有loding效果
            this.setState({ isLoading: true })
            //点击确认删除弹出框消失
            this.hanleCancleDelete()
          } else {
            //处理错误
          }
        })
        .catch(err => console.log(err))
    })
  }

  //点击列表里的删除，然后请求ajax数据对该条数据进行删除
  handleArticleDelete = (record) => {
    this.setState({
      edModalVisible: true,
      clickArticleId: record.id,
      clickArticleTitle: record.title
    })
  }

  //导出excel表
  exportXLSX = () => {
    const data = this.state.dataSource.reduce((result, item) => {
      result.push(Object.values(item))
      return result;
    }, [])
    data.unshift(Object.keys(this.state.dataSource[0]))

    const ws = XLSX.utils.aoa_to_sheet([['a', 'b'], [1, 2], [3, 4]]);
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, "SheetJs")
    XLSX.writeFile(wb, `文章列表${new Date().getTime()}.xlsx`)
  }

  //调用ajax方法
  componentDidMount() {
    this.getData()
  }


  //选中下来菜单显示隐藏
  handleColumnsChange = (selectedColumns) => {
    //删除叉选掉的一列数据
    const columns = this.initialColumns.filter(column => {
      //必须是选中的数组里包含的title或者是操作这个列才会被保留
      return selectedColumns.includes(column.title) || column.key === 'action' || column.key === 'title'
    })
    //返回这个值
    this.setState({
      columns
    })
  }

  render() {
    const extra = (
      <Fragment>
        {/* 下拉菜单 */}
        <Select
          mode="multiple"
          defaultValue={this.state.columnsOptions}
          onChange={this.handleColumnsChange}
          style={{ minWidth: 100 }}
        >
          {
            this.state.columnsOptions.map(item => {
              return <Select.Option key={item}>{item}</Select.Option>
            })
          }
        </Select>
        <Button onClick={this.exportXLSX}>导出excel</Button>
      </Fragment>
    )
    return (
      <Fragment>

        {/* 头部卡片 */}
        <Card
          title="文章列表"
          bordered={false}
          extra={extra}
          style={{ padding: 16 }}

        >
          {/* 内容表格 */}
          <Table
            dataSource={this.state.dataSource}
            columns={this.state.columns}
            loading={this.state.isLoading}
            rowKey={record => record.id}
            pagination={{
              pageSize: 10,
              showQuickJumper: true,
              showSizeChanger: true,
              hideOnSinglePage: true,
            }}
          />
        </Card>
        {/* 弹出框 */}
        <Modal
          title={"确认删除"}
          visible={this.state.edModalVisible}
          okText="别墨迹，你敢吗"
          cancelText="绕过他狗命吧"
          onCancel={this.hanleCancleDelete}
          onOk={this.handleDeleteButtonClick}
          confirmLoading={this.state.confirmLoading}
        >
          <Text> 确认要删除<Icon type="delete" /><Text type="danger">{this.state.clickArticleTitle}</Text>吗?
          删了就没有了哦，找不到了哟!!!!</Text>
        </Modal>
      </Fragment>
    )
  }
}
